package com.xinbochuang.machine.admin.controller.macroom;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinbochuang.machine.admin.domain.macRoom.EquShow;
import com.xinbochuang.machine.admin.domain.macRoom.Equipment;
import com.xinbochuang.machine.admin.domain.macRoom.EquipmentDetail;
import com.xinbochuang.machine.admin.domain.macRoom.json.DataJson;
import com.xinbochuang.machine.admin.domain.macRoom.json.Node;
import com.xinbochuang.machine.admin.service.macRoom.IEquShowService;
import com.xinbochuang.machine.admin.service.macRoom.IEquipmentDetailService;
import com.xinbochuang.machine.admin.service.macRoom.IEquipmentService;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄晓鹏
 * @date 2020-12-12
 */
@RestController
@RequestMapping("/equ-show")
public class EquShowController extends BaseController {

    @Resource
    private IEquShowService equShowService;

    @Resource
    private IEquipmentDetailService detailService;

    @Resource
    private IEquipmentService equipmentService;

    /**
     * 根据机房id查询所有节点
     */
    @PreAuthorize("@ss.hasPermi('system:macroom:show')")
    @GetMapping(value = "/{cabinetId}")
    public AjaxResult info(@PathVariable String cabinetId) {
        List<EquShow> points = equShowService.list(Wrappers.<EquShow>lambdaQuery().eq(EquShow::getCabinetId, cabinetId));
        List<Node> nodes = new ArrayList<>();
        for (EquShow point : points) {
            Node node = JSONUtil.toBean(point.getNode(), Node.class);
            node.setId(point.getId());
            node.setCabinetId(point.getCabinetId());
            node.setEquId(point.getEquId());
            EquipmentDetail detail = detailService.getOne(Wrappers.<EquipmentDetail>lambdaQuery().eq(EquipmentDetail::getEquId, point.getEquId()));
            Equipment equ = equipmentService.getById(point.getEquId());
            detail.setEquName(equ.getEquName());
            node.setEqu(detail);
            nodes.add(node);
        }
        DataJson json = new DataJson();
        json.setNodes(nodes);
        return AjaxResult.data(json);
    }

    /**
     * 保存节点数据
     */
    @PreAuthorize("@ss.hasPermi('system:macroom:save')")
    @PostMapping("/save")
    public AjaxResult save(@RequestBody List<Node> nodes) {
        return toAjax(equShowService.saveNodes(nodes));
    }

}

